import Layouts from '@/src/components/Layouts'
import React, { useState, useEffect } from 'react'
import { Card, Button, Table, Switch, Space, Popconfirm, message,Modal,Form,Input,Select } from "antd"
import Paginations from '@/src/components/Pagination'
import http from '@/src/utils/https'
import ConsultSearch from '@/src/components/ConsultSearch'
const Consult = () => {
  //分页
  let [page, setPage] = useState(1);
  let [pagesize, SetpageSize] = useState(10);
  let [total, SetTotal] = useState(100);
  const handelpage = (page: number, pagesize: number) => {
    // console.log(page, pagesize, "page")
    setPage(page)
    SetpageSize(pagesize)
  }
  const handelsize = (page: number, pagesize: number) => {
    // console.log(page, pagesize, "size")
    setPage(page)
    SetpageSize(pagesize)
  }
  //模糊搜素
  const handelsearch = (val: any) => {
    // console.log(val,'val')
    let obj = {};
    if(val.serTelName != ""){
      obj = { tit:val.serTelName }
    }
    if(val.type){
      obj = {...obj,status:val.type}
    }
    getconsultList(obj)
  }
  //获取资讯列表
  let [consultList, setConsultList] = useState([] as any)
  let [consultLists, setConsultLists] = useState([] as any)
  let [timer, setTimer] = useState(false)

  const getconsultList = async (obj = {}) => {
    if (timer) return
    http.get("/information", { params: obj }).then(res => {
      if (res.data.code == 200) {
        setConsultList(res.data.data)
        SetTotal(res.data.data.length)
      }
      setTimer(false)
    })
    setTimer(true)
  }
  useEffect(() => {
    if (consultList.length <= 0) {
      getconsultList()
    }
  }, [])
  //改变状态
  const onstatusChange = async (checked: boolean, id: any) => {
    let res = await http.post("/set/inforstatus", { id, status: checked })
    if (res.data.code == 200) {
      getconsultList()
    }
  };
  useEffect(() => {
    if (consultList.length > 0) {
      let newList = consultList.slice((page - 1) * pagesize, page * pagesize).map((item: any) => {
        item.key = item.id;
        item.created_at = new Date(item.created_at).toLocaleString()
        return item
      })
      // console.log(newList, "list")
      setConsultLists(newList)
    }
  }, [consultList, page, pagesize])

  let columns = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: 70
    },
    {
      title: '文章标题',
      dataIndex: 'tit',
      key: 'tit',
      width: 140
    },
    {
      title: '创建人',
      dataIndex: 'name',
      key: 'name',
      width: 70
    },
    {
      title: '创建日期',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 100
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render(_: any, item: any) {
        return <>
          <Switch checked={item.status == "1"} onChange={(e) => onstatusChange(e, item.id)} />
        </>
      }
    },
    {
      title: '操作',
      dataIndex: 'edit',
      key: 'edit',
      width: 100,
      render(_: any, item: any) {
        return <div>
          <Space>
            <Button type="link"onClick={() => handelshow(item)}>编辑</Button>
            <Button type="link" onClick={()=>handelete(item.id)}>删除</Button>
          </Space>
        </div>
      }
    },
  ] as any;

  //新增
  let [id,setid] = useState("")
  let [isedit,setEdit] = useState(true)
  //新增
  const handeladd = () =>{
    setEdit(false)
    showModal()
    form.setFieldValue("tit", '')
    form.setFieldValue("name", '')
    form.setFieldValue("status", '')
  }
  const showModal = () => {
    setIsModalOpen(true);
  };
  //删除
  const handelete = async (id:any) =>{
      let res = await http.delete("/del/information",{params:{id}})
      if(res.data.code==200){
        getconsultList()
      }
  }
  //编辑
  const handelshow = (obj: any) => {
    setEdit(true)
    setid(obj.id)
    showModal()
    form.setFieldValue("tit", obj.tit)
    form.setFieldValue("name", obj.name)
    form.setFieldValue("status", obj.status)
  }
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const onFinish =async (values: any) => {
    if(isedit){
      //编辑
      let res = await http.post("/edit/information",{id,...values})
      if(res.data.code==200){
        getconsultList()
      }
    }else{
      //新增
      console.log(values,"add")
      let res = await http.put("/add/information",{content:values});
      console.log(res,"add ")
      if(res.data.code==200){
        getconsultList()
      }
    }
    setIsModalOpen(false);
};

const onFinishFailed = (errorInfo: any) => {
    //输入框为空时提示消息
    errorInfo.errorFields.map((item:any)=>{
      message.warning(item.errors)
    }) 
};
  const [form] = Form.useForm<{ username: string; address: string, price: string, city: string }>();
  const [isModalOpen, setIsModalOpen] = useState(false);
  return (
    <Layouts>
      <Card style={{ width: "100%" }} bordered={false}>
        <h2>咨询管理</h2>
      </Card>
      {/* 搜索 */}
      <Card style={{ width: "100%" }} bordered={false}>
        <ConsultSearch handelsearch={handelsearch}></ConsultSearch>
      </Card>
      <Card style={{ width: "100%" }} bordered={false}  extra={<Button type="primary" onClick={handeladd}>新增</Button>}>
        {/* 内容 */}
        {
          consultLists.length > 0 &&
          <Table scroll={{ y: 540 }} style={{ height: 540, marginBottom: "10px" }} dataSource={consultLists} columns={columns} pagination={false} />
        }
      </Card>
      {/* //分页 */}
      <Card bordered={false} style={{ width: '100%', position: "sticky", left: "0", bottom: "0", zIndex: "9", minWidth: "800px", borderTop: "1px solid #ccc" }}>
        <Paginations total={total} page={page} pagesize={pagesize} onpage={handelpage} onsize={handelsize}></Paginations>
      </Card>


      <Modal title="编辑" open={isModalOpen} footer={false} onCancel={handleCancel}>
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          form={form}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="文章标题"
            name="tit"
            rules={[{ required: true, message: '哥们，输一下' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="创建人"
            name="name"
            rules={[{ required: true, message: '哥们，输一下' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item label="状态" name='status' rules={[{ required: true, message: '哥们，选一下' }]}>
            <Select style={{ width: 150 }} allowClear options={[
              {
                value: '1',
                label: '开启'
              },
              {
                value: '0',
                label: '关闭'
              }
            ]}></Select>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
              <Button type="default" onClick={handleCancel}>取消</Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </Layouts>
  )
}

export default Consult